﻿using System.Linq;
using Freetour.Application.Models.Membership;
using System;


namespace Freetour.Application.Persistence.Repositories.Membership
{
    internal class MembershipRepository : IMembershipRepository
    {
        public void Store(MembershipEntity membership)
        {
            using (var context = new MembershipRepositoryContext())
            {
                context.Memberships.AddObject(membership);
                context.SaveChanges();
            }
        }

        public bool TryGetMembershipByName(string userName, out MembershipEntity membership)
        {
            using (var context = new MembershipRepositoryContext())
            {
                var memberships = context.Memberships.Where(item => string.Compare(item.UserName, userName) == 0).ToArray();

                System.Diagnostics.Debug.Assert(memberships.Length == 1 || memberships.Length == 0);

                if (memberships.Length == 1)
                {
                    context.LoadProperty<MembershipEntity>(memberships[0], item => item.PersonalInfo);

                    membership = new MembershipEntity()
                        {
                            Id = memberships[0].Id,
                            UserName = memberships[0].UserName,
                            Password = memberships[0].Password,
                            PersonalInfo = memberships[0].PersonalInfo
                        };

                    return true;
                }
                else
                {
                    membership = null;
                    return false;
                }
            }
        }


        public bool IsExistedMembership(string userName)
        {
           using (var context = new MembershipRepositoryContext())
            {
                return context.Memberships.Count(item => string.Compare(item.UserName, userName) == 0) == 1 ? true : false;
            }
        }
    }
}
